package com.zyk.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangsan
 * @date 2021/4/7 14:28
 */
public class M0102 {

    // https://leetcode-cn.com/problems/check-permutation-lcci/
    // 辅助数组解
    public static boolean CheckPermutation(String s1, String s2) {
        if (s1.length() != s2.length()) {
            return false;
        }
        int N = s1.length();
        int[] help = new int[26];
        for (int i = 0; i < N; i++) {
            help[s1.charAt(i) - 'a']++;
        }
        for (int i = 0; i < N; i++) {
            if (help[s2.charAt(i) - 'a'] < 1) {
                return false;
            }
            help[s2.charAt(i) - 'a']--;
        }
        return true;
    }
    // 辅助map解
    public static boolean CheckPermutation2(String s1, String s2) {
        if (s1.length() != s2.length()) {
            return false;
        }
        int N = s1.length();
        HashMap<Character, Integer> countMap1 = new HashMap<>();
        HashMap<Character, Integer> countMap2 = new HashMap<>();
        for (int i = 0; i < N; i++) {
            countMap1.put(s1.charAt(i), countMap1.getOrDefault(s1.charAt(i), 0) + 1);
            countMap2.put(s2.charAt(i), countMap2.getOrDefault(s2.charAt(i), 0) + 1);
        }
        for (Map.Entry<Character, Integer> entry : countMap1.entrySet()) {
            if(!countMap2.getOrDefault(entry.getKey(), 0).equals(entry.getValue())) {
                return false;
            }
        }
        return true;
    }
    // 转成字符数组排序解
    public static boolean CheckPermutation3(String s1, String s2) {
        if (s1.length() != s2.length()) {
            return false;
        }
        char[] str1 = s1.toCharArray();
        char[] str2 = s2.toCharArray();
        Arrays.sort(str1);
        Arrays.sort(str2);
        return String.valueOf(str1).equals(String.valueOf(str2));
    }

    // for test
    public static void main(String[] args) {
        String s1 = "abc",
                s2 = "bad";
        System.out.println(CheckPermutation(s1, s2));
        System.out.println(CheckPermutation2(s1, s2));
        System.out.println(CheckPermutation3(s1, s2));
    }

}
